﻿using System;
using System.Collections.Generic;

namespace LitS3
{
    /// <summary>
    /// Gets all CloudFront distributions owned by you.
    /// </summary>
    public class GetAllDistributionsRequest : CloudFrontRequest<GetAllDistributionsResponse>
    {
        public GetAllDistributionsRequest(CloudFrontService service)
            : base(service, "GET", null, null)
        {
        }

        public GetAllDistributionsRequest(CloudFrontService service, string marker, int maxItems)
            : base(service, "GET", null, String.Format("Marker={0}&MaxItems={1}", marker, maxItems))
        {
        }
    }

    /// <summary>
    /// Contains the S3 response with all your owned CloudFront distributions.
    /// </summary>
    public sealed class GetAllDistributionsResponse : CloudFrontResponse
    {
        public string Marker { get; private set; }
        public string NextMarker { get; private set; }
        public int MaxItems { get; private set; }
        public bool IsTruncated { get; private set; }

        protected override void ProcessResponse()
        {
            // See http://docs.amazonwebservices.com/AmazonCloudFront/2008-06-30/DeveloperGuide/index.html?ListDistributions.html

            Reader.ReadStartElement("DistributionList");

            this.Marker = Reader.ReadElementContentAsString("Marker", "");

            // this is optional
            if (Reader.Name == "NextMarker")
                this.NextMarker = Reader.ReadElementContentAsString("NextMarker", "");

            this.MaxItems = Reader.ReadElementContentAsInt("MaxItems", "");

            this.IsTruncated = Reader.ReadElementContentAsBoolean("IsTruncated", "");
        }

        /// <summary>
        /// Provides a forward-only reader for efficiently enumerating through the response
        /// list of distributions.
        /// </summary>
        public IEnumerable<Distribution> Distributions
        {
            get
            {
                if (!Reader.IsEmptyElement)
                    while (Reader.Name == "DistributionSummary")
                        yield return new Distribution(Reader);
            }
        }
    }
}
